<template>
  <view class="my-travel-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="left" @click="goBack">
        <text class="iconfont icon-back">返回</text>
      </view>
      <view class="title">我的游记</view>
      <view class="right"></view>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="travel-list" scroll-y refresher-enabled :refresher-triggered="refreshing"
      @refresherrefresh="refreshList" @scrolltolower="loadMore">
      <!-- 游记列表 -->
      <view v-if="travelList.length > 0" class="travel-items">
        <view v-for="(item, index) in travelList" :key="item.id" class="travel-item">
          <view class="delete-wrapper">
            <u-button class="delete-btn" @click="deleteTravels(item.id)" size="mini" type="error">删除</u-button>
          </view>
          <!-- 游记内容 -->
          <view class="travel-content">
            <text class="travel-text">{{ item.content }}</text>

            <!-- 游记图片 -->
            <view class="travel-images" v-if="item.image" @click="navigateToDetail(item.id)">
              <view class="image-grid" :class="getImageGridClass(item.image)">
                <image v-for="(url, imgIndex) in item.image.split(',')" 
                       :key="imgIndex" 
                       :src="url" 
                       mode="aspectFill"
                      >
                </image>
              </view>
            </view>

            <!-- 互动信息 -->
            <view class="travel-meta">
              <view class="meta-item">
                <text class="meta-icon iconfont icon-view"></text>
                <text class="meta-count">{{ item.views || 0 }}</text>
              </view>
              <view class="meta-item">
                <text class="meta-icon iconfont icon-icon"></text>
                <text class="meta-count">{{ item.likes || 0 }}</text>
              </view>
              <view class="meta-item">
                <text class="meta-icon iconfont icon-shoucang"></text>
                <text class="meta-count">{{ item.favorites || 0 }}</text>
              </view>
              <text class="meta-time">{{ formatTime(item.createdAt) }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else-if="!loading" class="empty-state">
        <image class="empty-image" src="/static/images/empty.png" mode="aspectFit"></image>
        <text class="empty-text">还没有发布过游记哦~</text>
        <button class="publish-btn" @click="navigateToPublish">去发布</button>
      </view>

      <!-- 加载中 -->
      <view v-if="loading && !refreshing" class="loading">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 没有更多数据 -->
      <view v-if="!hasMoreData && travelList.length > 0" class="no-more">
        <text class="no-more-text">没有更多数据了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getUserTravelList, deleteTravel } from '@/api/travel'

// 响应式数据
const travelList = ref([])
const loading = ref(false)
const refreshing = ref(false)
const hasMoreData = ref(true)
const currentUser = ref(null)
const params = ref({
  page: 0,
  size: 10
})

// 计算属性
const isLoggedIn = computed(() => !!currentUser.value)

// 初始化用户信息
const initUserInfo = () => {
  try {
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo) {
      currentUser.value = userInfo
    } else {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  } catch (err) {
    console.error('获取用户信息失败:', err)
    uni.showToast({
      title: '获取用户信息失败',
      icon: 'none'
    })
  }
}

// 删除游记
const deleteTravels = async (id) => {
  try {
    const res = await uni.showModal({
      title: '提示',
      content: '确定删除该游记吗？',
      confirmText: '删除',
      confirmColor: '#ff4d4f'
    })
    
    if (res.confirm) {
      const result = await deleteTravel(id)
      if (result.code === 200) {
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        // 从列表中移除
        travelList.value = travelList.value.filter(item => item.id !== id)
      } else {
        throw new Error(result.message || '删除失败')
      }
    }
  } catch (err) {
    console.error('删除游记失败:', err)
    uni.showToast({
      title: err.message || '删除失败',
      icon: 'none'
    })
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now - date

  // 一小时内
  if (diff < 3600000) {
    const minutes = Math.floor(diff / 60000)
    return `${minutes}分钟前`
  }

  // 一天内
  if (diff < 86400000) {
    const hours = Math.floor(diff / 3600000)
    return `${hours}小时前`
  }

  // 一周内
  if (diff < 604800000) {
    const days = Math.floor(diff / 86400000)
    return `${days}天前`
  }

  // 显示日期
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

// 获取游记列表
const fetchTravelList = async (loadMore = false) => {
  if (loading.value || !currentUser.value) return

  loading.value = true

  try {
    const userId = currentUser.value.id
    const currentParams = { ...params.value, currentUserId: userId }

    const res = await getUserTravelList(userId, currentParams)

    if (res.code === 200) {
      if (loadMore) {
        travelList.value = [...travelList.value, ...res.data.content]
      } else {
        travelList.value = res.data.content
      }

      // 判断是否还有更多数据
      hasMoreData.value = !res.data.last
    } else {
      throw new Error(res.message || '获取游记列表失败')
    }
  } catch (err) {
    console.error('获取游记列表出错:', err)
    uni.showToast({
      title: err.message || '网络异常，请稍后重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 刷新列表
const refreshList = () => {
  refreshing.value = true
  params.value.page = 0
  fetchTravelList()
}

// 加载更多
const loadMore = () => {
  if (!hasMoreData.value || loading.value) return

  params.value.page++
  fetchTravelList(true)
}

// 跳转到游记详情页
const navigateToDetail = (id) => {
  uni.navigateTo({
    url: `/pages/discovery/travel-detail?id=${id}`
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 跳转到发布页面
const navigateToPublish = () => {
  if (!isLoggedIn.value) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }
  
  uni.navigateTo({
    url: '/package-discovery/pages/public-travel'
  })
}

// 预览图片
const previewImages = (imageStr, currentIndex) => {
  const urls = imageStr.split(',')
  uni.previewImage({
    urls,
    current: currentIndex
  })
}

// 获取图片网格的类名
const getImageGridClass = (imageStr) => {
  const count = imageStr.split(',').length
  if (count === 1) return 'single'
  if (count === 2) return 'double'
  if (count === 3) return 'triple'
  if (count === 4) return 'quad'
  return 'multi'
}

// 页面加载时获取数据
onMounted(() => {
  initUserInfo()
  fetchTravelList()
})
</script>

<style lang="scss" scoped>
.my-travel-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;

  .nav-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 44px;
    background-color: #fff;
    padding: 0 15px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    position: sticky;
    top: 0;
    z-index: 100;

    .left {
      font-size: 16px;
    }

    .title {
      font-size: 18px;
      font-weight: bold;
    }

    .right {
      width: 50px;
    }
  }

  .travel-list {
    flex: 1;

    .travel-items {
      padding: 10px;

      .travel-item {
        position: relative;
        margin-bottom: 15px;
        background-color: #fff;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

        .delete-wrapper {
          position: absolute;
          top: 10px;
          right: 10px;
          z-index: 10;

          .delete-btn {
            padding: 4px 8px;
            font-size: 12px;
            border-radius: 12px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          }
        }

        .travel-content {
          padding: 35px 15px 15px;
          
          .travel-text {
            font-size: 16px;
            line-height: 1.5;
            margin-bottom: 10px;
            color: #333;
          }

          .travel-images {
            margin: 10px 0;
            
            .image-grid {
              display: grid;
              gap: 6px;
              
              &.single {
                grid-template-columns: 1fr;
                
                image {
                  height: 200px;
                }
              }
              
              &.double {
                grid-template-columns: repeat(2, 1fr);
                
                image {
                  height: 150px;
                }
              }
              
              &.triple {
                grid-template-columns: repeat(3, 1fr);
                
                image {
                  height: 120px;
                }
              }
              
              &.quad {
                grid-template-columns: repeat(2, 1fr);
                grid-template-rows: repeat(2, 1fr);
                
                image {
                  height: 120px;
                }
              }
              
              &.multi {
                grid-template-columns: repeat(3, 1fr);
                
                image {
                  height: 100px;
                }
              }
              
              image {
                width: 100%;
                object-fit: cover;
                border-radius: 4px;
              }
            }
          }

          .travel-meta {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            color: #999;
            font-size: 14px;

            .meta-item {
              display: flex;
              align-items: center;
              margin-right: 15px;

              .meta-icon {
                font-size: 32rpx;
                color: #999;
              }

              .meta-count {
                color: #999;
              }
            }

            .meta-time {
              margin-left: auto;
              color: #999;
            }
          }
        }
      }
    }

    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 50px 0;

      .empty-image {
        width: 120px;
        height: 120px;
        margin-bottom: 20px;
      }

      .empty-text {
        font-size: 16px;
        color: #999;
        margin-bottom: 20px;
      }

      .publish-btn {
        background-color: #007aff;
        color: #fff;
        border-radius: 20px;
        font-size: 16px;
        padding: 8px 20px;
      }
    }

    .loading {
      text-align: center;
      padding: 15px 0;

      .loading-text {
        color: #999;
        font-size: 14px;
      }
    }

    .no-more {
      text-align: center;
      padding: 15px 0;

      .no-more-text {
        color: #999;
        font-size: 14px;
      }
    }
  }
}
</style>
